package com.wpf.system.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wpf.system.common.exception.CodeException;
import com.wpf.system.common.exception.CustomerAuthenionException;
import com.wpf.system.common.response.ResultVO;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();

        int code = 500;
        String str;
        if(exception instanceof AccountExpiredException){
            str = "账号过期，登录失败！";
        }else if(exception instanceof BadCredentialsException){
            str = "账号或密码错误，登录失败！";
        }else if(exception instanceof CredentialsExpiredException){
            str = "密码过期，登录失败！";
        }else if(exception instanceof DisabledException){
            str = "账号被禁用，登录失败！";
        }else if(exception instanceof LockedException){
            str = "账号被封禁，请联系管理员！";
        }else if(exception instanceof InternalAuthenticationServiceException){
            str = "账号不存在，登录失败！";
        }
        else if(exception instanceof CodeException){
            str = exception.getMessage();
        }else if(exception instanceof CustomerAuthenionException){
            code = 600;
            str = exception.getMessage();
        }else{
            str = "登录失败！";
        }
        String res =  JSONObject.toJSONString(new ResultVO(str,code,null), SerializerFeature.DisableCircularReferenceDetect);

        out.write(res.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
